<?php
namespace app\erp\model;

use think\Model;
use traits\model\SoftDelete;
use think\Cache;

class Invoicedb extends Model
{
    use SoftDelete;

    public $param = array();

    protected $name = 'invoice';

    protected $pk = 'invoice_id';

    protected $type = [
        'create_time' => 'timestamp:Y-m-d H:i',
        'delete_time' => 'timestamp:Y-m-d H:i',
        'invoice_time' => 'timestamp:Y-m-d H:i',
        'post_time' => 'timestamp:Y-m-d H:i',
        'receive_time' => 'timestamp:Y-m-d H:i',
        'draw_time' => 'timestamp:Y-m-d H:i'
    ];
    // 自动完成时间转换
    protected $autoWriteTimestamp = true;

    protected $insert = [
        'partner_id' => PARTNER_ID,
        'site_id',
        'state' => 1
    ];

    protected function cache_name($name)
    {
        $new_arr = $this->param;
        $new_arr['partner_id'] = PARTNER_ID;
        if (! isset($new_arr['site_id'])) {
            $new_arr['site_id'] = SITE_ID;
        }
        ksort($new_arr);
        $param_str = http_build_query($new_arr);
        return md5($name . $param_str);
    }

    protected function setSiteIdAttr($value)
    {
        if (! $value) {
            return SITE_ID;
        }
        if ($value == 0) {
            return null;
        }
        return $value;
    }

    public function setCartIdsAttr($value)
    {
        if (is_array($value)) {
            return implode(',', $value);
        } else {
            return $value;
        }
    }

    public function setOrderNosAttr($value)
    {
        if (is_array($value)) {
            return implode(',', $value);
        } else {
            return $value;
        }
    }

    public function scopeOrderNo($query, $order_no)
    {
        if (is_array($order_no)) {
            $temp = $order_no;
        } else {
            $temp = explode(',', $order_no);
        }
        if (count($temp) == 1) {
            $query->where('order_nos', 'like', '%' . $order_no . '%');
        } else {
            $query->where('', 'exp', 'find_in_set(`order_nos`,"' . $temp . '")');
        }
    }

    public function scopeMemberId($query, $member_id)
    {
        $query->where('member_id', $member_id);
    }

    public function scopeInvoiceId($query, $invoice_id)
    {
        $query->where('invoice_id', $invoice_id);
    }

    public function scopeApplyState($query, $apply_state)
    {
        $query->where('apply_state', $apply_state);
    }

    public function scopeState($query, $state)
    {
        if (is_array($state)) {
            $query->where('state', 'IN', $state);
        } else {
            $query->where('state', $state);
        }
    }

    public function scopeBuilderType($query, $builder_type)
    {
        $query->where('builder_type', $builder_type);
    }

    public function scopeInvoiceTitle($query, $invoice_title)
    {
        $query->where('invoice_title', 'like', '%' . $invoice_title . '%');
    }

    public function scopeInvoiceDuty($query, $invoice_duty)
    {
        $query->where('invoice_duty', 'like', '%' . $invoice_duty . '%');
    }

    public function scopeDrawState($query, $draw_state)
    {
        $query->where('draw_state', $draw_state);
    }

    public function scopePostState($query, $post_state)
    {
        $query->where('post_state', $post_state);
    }

    public function scopeReceiveState($query, $receive_state)
    {
        $query->where('receive_state', $receive_state);
    }

    public function scopeDrawAdminId($query, $draw_admin_id)
    {
        $query->where('draw_admin_id', $draw_admin_id);
    }

    public function scopeIsInvoice($query, $is_invoice)
    {
        $query->where('is_invoice', $is_invoice);
    }
    // 基础查询
    public function base($query)
    {
        $field = $this->getDeleteTimeField(true);
        if ($field) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->onlyTrashed();
            } else {
                $query->useSoftDelete($field);
            }
        }
        $query->where('partner_id', PARTNER_ID);
        if (isset($this->param['site_id'])) {
            if ($this->param['site_id'] == 0 || $this->param['site_id'] == '') {
                $query->where('site_id', null);
            } elseif ($this->param['site_id'] != - 1) {
                $query->where('site_id', $this->param['site_id']);
            }
        } else {
            if (! empty(SITE_ID)) {
                $query->where('site_id', SITE_ID);
            } else {
                $query->where('site_id', null);
            }
        }
        if (isset($this->param['order_no']) && $this->param['order_no']) {
            $query->orderNo($this->param['order_no']);
        }
        if (isset($this->param['order_nos']) && $this->param['order_nos']) {
            $query->orderNo($this->param['order_nos']);
        }
        if (isset($this->param['member_id']) && $this->param['member_id']) {
            $query->memberId($this->param['member_id']);
        }
        if (isset($this->param['invoice_id']) && $this->param['invoice_id']) {
            $query->invoiceId($this->param['invoice_id']);
        }
        if (isset($this->param['apply_state']) && $this->param['apply_state']) {
            $query->applyState($this->param['apply_state']);
        }
        if (isset($this->param['state']) && $this->param['state']) {
            $query->state($this->param['state']);
        }
        if (isset($this->param['builder_type']) && $this->param['builder_type']) {
            $query->builderType($this->param['builder_type']);
        }
        if (isset($this->param['invoice_title']) && $this->param['invoice_title']) {
            $query->invoiceTitle($this->param['invoice_title']);
        }
        if (isset($this->param['invoice_duty']) && $this->param['invoice_duty']) {
            $query->invoiceDuty($this->param['invoice_duty']);
        }
        if (isset($this->param['draw_state']) && $this->param['draw_state']) {
            $query->drawState($this->param['draw_state']);
        }
        if (isset($this->param['post_state']) && $this->param['post_state']) {
            $query->postState($this->param['post_state']);
        }
        if (isset($this->param['receive_state']) && $this->param['receive_state']) {
            $query->receiveState($this->param['receive_state']);
        }
        if (isset($this->param['draw_admin_id']) && $this->param['draw_admin_id']) {
            $query->drawAdminId($this->param['draw_admin_id']);
        }
        if (isset($this->param['is_invoice']) && $this->param['is_invoice']) {
            $query->isInvoice($this->param['is_invoice']);
        }
    }

    public function ajaxFind()
    {
        $data = $this->master()
            ->order('invoice_id desc')
            ->find();
        if ($data) {
            if (! isset($this->param['no_need_invoice_handle'])) {
                $data = $this->handleData($data->toArray());
            }
            return $data;
        } else {
            return array();
        }
    }

    public function ajaxCount()
    {
        $data = $this->cache($this->cache_name('invoice_count'), 86400, 'invoice')
            ->count();
        return $data;
    }

    public function ajaxList()
    {
        $data = $this->cache($this->cache_name('invoice_list'), 86400, 'invoice')
            ->page($this->param['page'], $this->param['limit'])
            ->order($this->param['_o'], $this->param['_b'])
            ->select();
        if ($data) {
            $data = $data->toArray();
            if (! isset($this->param['no_need_invoice_handle'])) {
                foreach ($data as $key => $val) {
                    $data[$key] = $this->handleData($val);
                }
            }
            return $data;
        } else {
            return array();
        }
    }

    public function ajaxPage()
    {
        $return['data'] = $this->ajaxList();
        $return['count'] = $this->ajaxCount();
        return $return;
    }

    public function ajaxSelect()
    {
        $data = $this->cache($this->cache_name('invoice_select'), 86400, 'invoice')
            ->select();
        if ($data) {
            $data = $data->toArray();
            foreach ($data as $key => $val) {
                $data[$key] = $this->handleData($val);
            }
            return $data;
        } else {
            return array();
        }
    }
    // 确认开票
    public function makeInvoice()
    {
        $data = $this->param;
        $data['state'] = 2;
        $data['invoice_time'] = time();
        $this->save($data, [
            'invoice_id' => $this->param['invoice_id']
        ]);
        // 处理订单开票状态
        $get_invoice_info = $this->ajaxFind();
        $get_order_nos = explode(',', $get_invoice_info['order_nos']);
        $orderdb = new Orderdb();
        for ($i = 0; $i < count($get_order_nos); $i ++) {
            $orderdb->param['event'] = 'make_invoice';
            $orderdb->param['order_no'] = $get_order_nos[$i];
            $orderdb->param['cart_ids'] = explode(',', $get_invoice_info['cart_ids']);
            $orderdb->editOrder();
        }
        Cache::clear('invoice');
        return 'success';
    }
    // 保存数据
    public function ajaxSave()
    {
        if (isset($this->param['invoice_id']) && $this->param['invoice_id'] != '') {
            if ($this->param['field'] == 'apply_state' && $this->param['value'] == 1) {
                // 申请开票
                $data['draw_admin_id'] = MEMBER_ID;
                $data['state'] = 1;
            }
            if ($this->param['field'] == 'draw_state' && $this->param['value'] == 1) {
                // 领取发票
                $data['draw_time'] = time();
            }
            if ($this->param['field'] == 'state' && $this->param['value'] == 3) {
                // 发票驳回
                $data['reject_reason'] = $this->param['reject_reason'];
                // $data['apply_state'] = 2;
                $get_invoice = $this->useGlobalScope(false)
                    ->where('invoice_id', $this->param['invoice_id'])
                    ->find()
                    ->toArray();
                if ($get_invoice['is_invoice'] == 2) {
                    // 独立开票 复制一条信息
                    $copy_data = $get_invoice;
                    $copy_data['apply_state'] = 2;
                    $copy_data['state'] = 1;
                    $copy_data['reject_reason'] = '';
                    unset($copy_data['invoice_id']);
                    $this->save($copy_data);
                    unset($this->data['invoice_id']);
                }
            }
            if ($this->param['field'] == 'post_state' && $this->param['value'] = 1) {
                // 配送发票
                $data['post_time'] = time();
                $data['post_addr'] = $this->param['post_addr'];
                $data['post_realname'] = $this->param['post_realname'];
                $data['post_phone'] = $this->param['post_phone'];
                $data['express'] = $this->param['express'];
                $data['express_no'] = $this->param['express_no'];
            }
            if ($this->param['field'] == 'receive_state' && $this->param['value'] = 1) {
                // 发票已收货
                $data['receive_time'] = time();
            }
            // 修改
            $data[$this->param['field']] = $this->param['value'];
            $this->save($data, [
                'invoice_id' => $this->param['invoice_id']
            ]);
        } else {
            // 新增 申请开票
            if (! isset($this->param['invoice_money'])) {
                $this->param['invoice_money'] = $this->param['order_money'];
            }
            if (isset($this->param['apply_state']) && $this->param['apply_state'] == 1) {
                $this->param['draw_admin_id'] = MEMBER_ID;
            }
            $this->allowField(true)->save($this->param);
        }
        Cache::clear('invoice');
        return 'success';
    }
    // 软删除
    public function ajaxDelete()
    {
        if (isset($this->param['invoice_id'])) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->destroy(function ($query) {
                    $query->where('invoice_id', 'IN', $this->param['invoice_id']);
                }, true);
            } else {
                $this->destroy(function ($query) {
                    $query->where('invoice_id', 'IN', $this->param['invoice_id']);
                });
            }
            Cache::clear('invoice');
            return 'success';
        }
    }
    // 数据处理
    protected function handleData($val)
    {
        $uploaddb = new Uploaddb();
        $memberdb = new Memberdb();
        foreach ($val as $k => $v) {
            $val[$k] = $v;
            switch ($k) {
                case 'state':
                    if ($v == 1) {
                        $val['state_text'] = '<font style=color:#FFB800>申请中</font>';
                    } elseif ($v == 2) {
                        $val['state_text'] = '<font style=color:#5FB878>已开票</font>';
                    } else {
                        $val['state_text'] = '<font style=color:#FF5722>被驳回</font>';
                    }
                    break;
                case 'cart_ids':
                    if (isset($this->param['need_cart_info']) && $this->param['need_cart_info'] == 'yes') {
                        $cartdb = new Cartdb();
                        $cartdb->param['cart_id'] = explode(',', $v);
                        $cartdb->param['need_goods_title'] = 'yes';
                        $get_cart = $cartdb->ajaxList();
                        $val['cart_info'] = $get_cart['list'];
                    }
                    break;
                case 'express':
                    $val['express_name'] = changeExpress($v);
                    break;
                case 'builder_type':
                    if ($v == 1) {
                        $val['builder_type_text'] = '纸质发票';
                    } else {
                        $val['builder_type_text'] = '电子发票';
                    }
                    break;
                case 'invoice_type':
                    if ($v == 1) {
                        $val['invoice_type_text'] = '普通发票';
                    } elseif ($v == 2) {
                        $val['invoice_type_text'] = '增值税发票';
                    } elseif ($v == 3) {
                        $val['builder_type'] = 2;
                        $val['builder_type_text'] = '电子发票';
                        $val['invoice_type_text'] = '增值税发票';
                    }
                    break;
                case 'invoice_money':
                    $val['invoice_money'] = number_format($val['invoice_money'] / 100, 2, '.', '');
                    break;
                case 'invoice_proof':
                    if ($val['invoice_proof']) {
                        $val['invoice_proof'] = $uploaddb->getFind($val['invoice_proof']);
                    }
                    break;
                case 'order_nos':
                    if (isset($this->param['need_post_info']) && $this->param['need_post_info'] == 'yes') {
                        // 需要订单配送信息
                        $orderdb = new Orderdb();
                        $temp = explode(',', $v);
                        $orderdb->param['order_no'] = $temp[0];
                        $orderdb->param['field'] = 'shopping_id';
                        $get_order = $orderdb->ajaxField();
                        $shoppingdb = new Shoppingdb();
                        $shoppingdb->param['shopping_id'] = $get_order['shopping_id'];
                        $get_shopping = $shoppingdb->ajaxFind();
                        $val['shopping_info'] = $get_shopping;
                        $val['init_express_no'] = 'PS' . base_convert(uniqid(), 16, 10);
                    }
                    break;
                case 'draw_admin_id':
                    if ($v) {
                        $memberdb->param['member_id'] = $v;
                        $get_member = $memberdb->ajaxFind();
                        $val['draw_name'] = $get_member['realname'];
                    }
                    break;
                default:
                    break;
            }
        }
        return $val;
    }
}